package cn.song.logread.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域
 *
 * @author SongRenShuo
 * @date 2025/03/16
 */
@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //允许任何域名
        corsConfiguration.addAllowedOriginPattern("*");
        //允许任何头
        corsConfiguration.addAllowedHeader("*");
        //允许任何方法
        corsConfiguration.addAllowedMethod("*");
        //这两句不加不能跨域上传文件，
        corsConfiguration.setAllowCredentials(true);
        //加上去就可以了
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }

    /**
     * cors过滤器
     *
     *
     * @date 2025/03/16
     * @return {@link CorsFilter }
     * @author SongRenShuo
     */
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //注册
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

}
